<template>
  <div id="printContent">
    <el-form v-if="!is_print" ref="cuForm" v-loading="formLoading" style="width: 90%;margin: 0 auto;position: relative"
             :model="cuForm"
             :disabled="formDisabled"
    >
      <div>
        <el-form-item prop="name"
                      label="报销名称"
                      style="width:400px;margin: 0 auto"
                      :rules="{required: true, message: '报销名称不能为空', trigger: 'blur'}"
        >
          <el-input
            v-model="cuForm.name"
            clearable
            placeholder="请输入报销名称"
            style="width: 300px"
          />
        </el-form-item>
      </div>
      <div style="margin: 5px auto">

        <div class="flex flex-no-wrap justify-between">
          <el-form-item label-width="80px" label="类型" prop="type"
                        :rules="{required: true, message: '类型不能为空', trigger: 'change'}"
          >
            <el-radio-group v-model="cuForm.type" @input="typeChange">
              <el-radio :label="1">普通</el-radio>
              <el-radio :label="2">维护</el-radio>
              <el-radio :label="3">销售单</el-radio>
            </el-radio-group>
          </el-form-item>
          <div>
            <el-form-item v-if="cuForm.type === 3" style="position: relative" label-width="80px" label="销售单"
                          prop="bill_sale_id"
                          :rules="{required: true, message: '销售单不能为空', trigger: 'change'}"
            >
              <el-select v-model="cuForm.bill_sale_id" style="width: 340px" size="mini"
                         clearable filterable @change="billSaleChange"
              >
                <el-option v-for="item in sale_list" :key="item.id" :value="item.id"
                           :label="item.contract_num+'——'+item.actual_execute_time_start+'~'+item.actual_execute_time_end"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="cuForm.type === 2" label-width="80px" label="合同" prop="contract_id"
                          :rules="{required: true, message: '合同不能为空', trigger: 'change'}"
            >
              <el-select v-model="cuForm.contract_id" style="width: 400px" size="mini"
                         clearable filterable
              >
                <el-option v-for="item in contract_list" :key="item.id" :value="item.id"
                           :label="item.part_a+'——'+item.contract_num+'('+item.contract_begin_date+'~'+item.contract_end_date+')'"
                />
              </el-select>
            </el-form-item>
          </div>
        </div>
      </div>
      <table class="mailTable" style="margin-top: 10px">
        <tr class="firstTr">
          <td class="column firstTd">
            <span class="tip">*</span>类目
          </td>
          <td class="column">
            <span class="tip">*</span>品名
          </td>
          <td class="column">
            <span class="tip">*</span>单位
          </td>
          <td class="column">
            <span class="tip">*</span>数量
          </td>
          <td class="column">
            <span class="tip">*</span>金额
          </td>
          <td class="column" style="position: relative">
            <span class="tip">*</span>用途
            <i v-if="!formDisabled" class="el-icon-circle-plus-outline"
               style="color: #67C23A;font-size: 25px;position: absolute;top: 17px;right: -37px" @click="addItem"
            />
          </td>
        </tr>
        <tr v-for="(item,index) in cuForm.reimburseApplyDetailList">
          <td class="column firstTd">
            <el-form-item :prop="'reimburseApplyDetailList[' + index + '].category_id'"
                          :rules="{required: true, message: '类目不能为空', trigger: 'change'}"
            >
              <el-select v-model="item.category_id" clearable placeholder="请选择类目" @change="(val)=>{onChange(item,val)}">
                <el-option v-for="tmp in category_arr" :key="tmp.id" :label="tmp.name" :value="tmp.id"/>
              </el-select>
            </el-form-item>
          </td>
          <td class="column">
            <el-form-item :prop="'reimburseApplyDetailList.' + index + '.product_name'"
                          :rules="{required: true, message: '品名不能为空', trigger: 'blur'}"
            >
              <el-input v-model="item.product_name" placeholder="请输入品名" clearable/>
            </el-form-item>
          </td>
          <td class="column">
            <el-form-item :prop="'reimburseApplyDetailList.' + index + '.unit'"
                          :rules="{required: true, message: '单位不能为空', trigger: 'blur'}"
            >
              <el-input v-model="item.unit" placeholder="请输入单位" clearable/>
            </el-form-item>
          </td>
          <td class="column">
            <el-form-item :prop="'reimburseApplyDetailList.' + index + '.quantity'"
                          :rules="[{required: true, message: '数量不能为空', trigger: 'blur'},
                                   {required: true, message: '数量不能为空', trigger: 'change'}]"
            >
              <el-input-number v-model="item.quantity" controls-position="right" placeholder="请输入数量" :min="1"
                               clearable
              />
            </el-form-item>
          </td>
          <td class="column">
            <el-form-item :prop="'reimburseApplyDetailList.' + index + '.amount'"
                          :rules="{required: true, message: '金额不能为空', trigger: 'blur'}"
            >
              <el-input v-model="item.amount" type="number" step="0.01" placeholder="请输入金额" clearable/>
            </el-form-item>
          </td>
          <td class="column" style="padding: 10px;position: relative">
            <el-form-item :prop="'reimburseApplyDetailList.' + index + '.reason'"
                          :rules="{required: true, message: '用途不能为空', trigger: 'blur'}"
            >
              <el-input v-model="item.reason" type="textarea" style="width: 100%;" placeholder="请输入用途" clearable
                        :autosize="{ minRows: 2, maxRows: 4}"
              />
            </el-form-item>
            <i v-show="cuForm.reimburseApplyDetailList && cuForm.reimburseApplyDetailList.length > 1"
               v-if="!formDisabled"
               class="el-icon-remove-outline"
               style="color: #F56C6C;font-size: 25px;position: absolute;top: 23px;right: -37px"
               @click="removeItem(1,index)"
            />
          </td>
        </tr>
        <tr>
          <td class="column firstTd">
            合计：
          </td>
          <td class="column" colspan="2">
            {{ cuForm.total_amount }}
          </td>
          <td class="column">
            大写：
          </td>
          <td class="column" colspan="2">
            {{ bigMoneyStr }}
          </td>
        </tr>
        <tr>
          <td class="column firstTd">
            对私报销：
          </td>
          <td class="column" colspan="5" style="text-align: left;padding: 10px">
            <el-tooltip v-if="!formDisabled && cuForm.type ===3 && !cuForm.bill_sale_id" effect="dark" content="请先选择销售单"
                        placement="top-start"
            >
              <span>
                <el-button size="small" type="primary" :disabled="true">对私报销</el-button>
              </span>
            </el-tooltip>
            <el-button
              v-else-if="!formDisabled&&( cuForm.type!==3 || (cuForm.type ===3 && cuForm.reimbursePrivateDetailList.length===0 && cuForm.bill_sale_id))"
              size="small"
              type="primary" @click="showPrivateDialog()"
            >对私报销
            </el-button>
            <div v-for="(item,index) in cuForm.reimbursePrivateDetailList" :key="index">
              姓名：{{ item.name }}&nbsp;&nbsp;&nbsp;&nbsp;
              <span v-if="item.id_card">证件号码：{{ item.id_card }}&nbsp;&nbsp;&nbsp;&nbsp;</span>
              报销金额：{{ item.amount }}&nbsp;&nbsp;&nbsp;&nbsp;
              支付方式：{{ item.pay_type === 1 ? '现金' : item.pay_type === 2 ? '支票' : '网银汇划' }}&nbsp;&nbsp;&nbsp;&nbsp;
              <span v-if="item.pay_type === 3">银行名称：{{ item.bank_name }}&nbsp;&nbsp;&nbsp;&nbsp;</span>
              <span v-if="item.pay_type === 3">开户户名：{{ item.bank_card_name }}&nbsp;&nbsp;&nbsp;&nbsp;</span>
              <span v-if="item.pay_type === 3">开户账号：{{ item.bank_account }}&nbsp;&nbsp;&nbsp;&nbsp;</span>
              <span v-if="item.pay_type === 2">支票抬头：{{ item.cheque_payable }}&nbsp;&nbsp;&nbsp;&nbsp;</span>
              <el-button v-if="!formDisabled" type="text" style="color: #409EFF;text-decoration: underline"
                         @click="showPrivateDialog(index)"
              >
                编辑
              </el-button>
              <el-button v-if="!formDisabled" type="text" style="color:#F56C6C;text-decoration: underline"
                         @click="removeItem(2,index)"
              >删除
              </el-button>
            </div>
          </td>
        </tr>
        <tr v-if="cuForm.type === 1">
          <td class="column firstTd">
            对公报销：
          </td>
          <td class="column" colspan="5" style="text-align: left;padding: 10px">
            <el-button v-if="!formDisabled" size="small" type="primary" @click="showPublicDialog()">对公报销</el-button>
            <div v-for="(item,index) in cuForm.reimbursePublicDetailList" :key="index">
              公司名称：{{ item.company_name }}&nbsp;&nbsp;&nbsp;&nbsp;
              报销金额：{{ item.amount }}&nbsp;&nbsp;&nbsp;&nbsp;
              开户行名称：{{ item.bank_name }}&nbsp;&nbsp;&nbsp;&nbsp;
              开户账号：{{ item.bank_account }}&nbsp;&nbsp;&nbsp;&nbsp;
              <el-button v-if="!formDisabled" type="text" style="color: #409EFF;text-decoration: underline"
                         @click="showPublicDialog(index)"
              >
                编辑
              </el-button>
              <el-button v-if="!formDisabled" type="text" style="color:#F56C6C;text-decoration: underline"
                         @click="removeItem(3,index)"
              >删除
              </el-button>
            </div>
          </td>
        </tr>
        <tr>
          <td class="column firstTd">
            附件：
          </td>
          <td class="column" colspan="5" style="text-align: left;padding: 10px">
            <el-upload
              :class="formDisabled?'upload_none':''"
              :action="upFileUrl"
              :headers="uploadHeaders"
              :on-preview="handlePreview"
              :before-remove="beforeRemove"
              :on-remove="onRemove"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :before-upload="beforeUpload"
              multiple
              :file-list="cuForm.reimburseApplyAttachmentList"
            >
              <el-button v-if="!formDisabled" size="small" type="primary">上传附件
              </el-button>
            </el-upload>
          </td>
        </tr>
      </table>
      <div class="flex flex-no-wrap justify-between">
        <span style="line-height: 32px">申请人： {{ userName }}</span>
        <span style="line-height: 32px">提交日期： {{ cuForm.submit_time }}</span>
      </div>
      <el-form v-if="cuForm.flow_status === 4">
        <el-button v-if="!is_print" size="small" style="position: absolute;top:-5px;right: -5px" @click="print">打印
        </el-button>
      </el-form>
    </el-form>
    <el-form v-if="is_print" ref="cuForm" v-loading="formLoading" style="width: 90%;margin: 0 auto;position: relative"
             :model="cuForm"
    >
      <div class="header">
        报销名称：{{ cuForm.name }}
      </div>
      <div style="margin: 5px auto">
        <div class="flex flex-no-wrap justify-between">
          类型：{{ cuForm.type === 1 ? '普通' : cuForm.type === 2 ? '维护' : '销售单' }}
          <div>
            <span v-if="cuForm.type === 3" style="position: relative"
            >销售单：{{
                cuForm.sale_contract_num + '——' + cuForm.actual_execute_time_start + '~' + cuForm.actual_execute_time_end
              }}</span>
            <span v-if="cuForm.type === 2" style="position: relative"
            >合同：{{
                cuForm.part_a + '——' + cuForm.contract_num + '(' + cuForm.contract_begin_date + '~' + cuForm.contract_end_date + ')'
              }}</span>
          </div>
        </div>
      </div>
      <table class="mailTable" style="margin-top: 10px">
        <tr class="firstTr">
          <td class="column firstTd">
            <span class="tip">*</span>类目
          </td>
          <td class="column">
            <span class="tip">*</span>品名
          </td>
          <td class="column">
            <span class="tip">*</span>单位
          </td>
          <td class="column">
            <span class="tip">*</span>数量
          </td>
          <td class="column">
            <span class="tip">*</span>金额
          </td>
          <td class="column" style="position: relative">
            <span class="tip">*</span>用途
          </td>
        </tr>
        <tr v-for="(item,index) in cuForm.reimburseApplyDetailList" :key="index">
          <td class="column firstTd">
            {{ item.category_name }}
          </td>
          <td class="column">
            {{ item.product_name }}
          </td>
          <td class="column">
            {{ item.unit }}
          </td>
          <td class="column">
            {{ item.quantity }}
          </td>
          <td class="column">
            {{ item.amount }}元
          </td>
          <td class="column" style="padding: 10px;position: relative">
            {{ item.reason }}
          </td>
        </tr>
        <tr>
          <td class="column firstTd">
            合计：
          </td>
          <td class="column" colspan="2">
            {{ cuForm.total_amount }}
          </td>
          <td class="column">
            大写：
          </td>
          <td class="column" colspan="2">
            {{ bigMoneyStr }}
          </td>
        </tr>
        <tr>
          <td class="column firstTd">
            对私报销：
          </td>
          <td class="column" colspan="5" style="text-align: left;padding: 10px">
            <div v-for="(item,index) in cuForm.reimbursePrivateDetailList" :key="index">
              姓名：{{ item.name }}&nbsp;&nbsp;&nbsp;&nbsp;
              <span v-if="item.id_card">证件号码：{{ item.id_card }}&nbsp;&nbsp;&nbsp;&nbsp;</span>
              报销金额：{{ item.amount }}&nbsp;&nbsp;&nbsp;&nbsp;
              支付方式：{{ item.pay_type === 1 ? '现金' : item.pay_type === 2 ? '支票' : '网银汇划' }}&nbsp;&nbsp;&nbsp;&nbsp;
              <span v-if="item.pay_type === 3">银行名称：{{ item.bank_name }}&nbsp;&nbsp;&nbsp;&nbsp;</span>
              <span v-if="item.pay_type === 3">开户户名：{{ item.bank_card_name }}&nbsp;&nbsp;&nbsp;&nbsp;</span>
              <span v-if="item.pay_type === 3">开户账号：{{ item.bank_account }}&nbsp;&nbsp;&nbsp;&nbsp;</span>
              <span v-if="item.pay_type === 2">支票抬头：{{ item.cheque_payable }}&nbsp;&nbsp;&nbsp;&nbsp;</span>
            </div>
          </td>
        </tr>
        <tr v-if="cuForm.type === 1">
          <td class="column firstTd">
            对公报销：
          </td>
          <td class="column" colspan="5" style="text-align: left;padding: 10px">
            <div v-for="(item,index) in cuForm.reimbursePublicDetailList" :key="index">
              公司名称：{{ item.company_name }}&nbsp;&nbsp;&nbsp;&nbsp;
              报销金额：{{ item.amount }}&nbsp;&nbsp;&nbsp;&nbsp;
              开户行名称：{{ item.bank_name }}&nbsp;&nbsp;&nbsp;&nbsp;
              开户账号：{{ item.bank_account }}&nbsp;&nbsp;&nbsp;&nbsp;
            </div>
          </td>
        </tr>
      </table>
      <div class="flex flex-no-wrap justify-between">
        <span style="line-height: 32px">申请人： {{ userName }}</span>
        <span style="line-height: 32px">提交日期： {{ cuForm.submit_time }}</span>
      </div>
      <el-form v-if="cuForm.flow_status === 4">
        <el-button v-if="!is_print" size="small" style="position: absolute;top:-5px;right: -5px" @click="print">打印
        </el-button>
      </el-form>
    </el-form>
    <FlowBtnRow v-if="!is_print" :form-name="'cuForm'" :is-new-data="is_created" :can-check="cuForm.can_check"
                :is-applyer="cuForm.flow_applyer_id == userId" :flow-status="cuForm.flow_status"
                :data-id="(params || {}).id || ((params || {}).handle_param || {}).id"
                :flow-type="14" @save="save" @submit="submit" @pass="pass" @returnBack="returnBack"
                @delete="remove" @actualDelete="actualDelete"
    />
    <el-dialog :title="edit?'编辑':'添加'+'对公报销'" :visible.sync="publicDialogVisible" width="500px" center
               @close="closePublicDialog"
    >
      <el-form ref="reimbursePublicDetailForm" label-width="100px" :model="reimbursePublicDetail"
               :rules="reimbursePublicDetailRules"
      >
        <el-form-item label="公司名称" prop="company_name">
          <el-input v-model="reimbursePublicDetail.company_name" placeholder="请输入公司名称"/>
        </el-form-item>
        <el-form-item label="报销金额" prop="amount">
          <el-input v-model="reimbursePublicDetail.amount" type="number" step="0.01" placeholder="请输入报销金额">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="开户行名称" prop="bank_name">
          <el-input v-model="reimbursePublicDetail.bank_name" placeholder="请输入开户行名称"/>
        </el-form-item>
        <el-form-item label="开户账号" prop="bank_account">
          <el-input v-model="reimbursePublicDetail.bank_account" placeholder="请输入开户账号"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="publicDialogVisible = false">取 消</el-button>
        <el-button type="primary" size="mini" @click="saveReimbursePublicDetail">保 存</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="edit?'编辑':'添加'+'对私报销'" :visible.sync="privateDialogVisible" width="500px" center
               @close="closePrivateDialog"
    >
      <el-form ref="reimbursePrivateDetailForm" label-width="100px" :model="reimbursePrivateDetail"
               :rules="reimbursePrivateDetailRules"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="reimbursePrivateDetail.name" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="证件号码" prop="id_card">
          <el-input v-model="reimbursePrivateDetail.id_card" placeholder="请输入证件号码"/>
        </el-form-item>
        <el-form-item label="报销金额" prop="amount">
          <el-input v-model="reimbursePrivateDetail.amount" type="number" step="0.01" placeholder="请输入报销金额"
                    @input="inputChange"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="支付方式" prop="pay_type">
          <el-radio-group v-model="reimbursePrivateDetail.pay_type">
            <el-radio :label="1">现金</el-radio>
            <el-radio :label="2">支票</el-radio>
            <el-radio :label="3">网银汇划</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="reimbursePrivateDetail.pay_type === 3" label="开户银行" prop="bank_name">
          <el-input v-model="reimbursePrivateDetail.bank_name" placeholder="请输入开户银行"/>
        </el-form-item>
        <el-form-item v-if="reimbursePrivateDetail.pay_type === 3" label="开户户名" prop="bank_card_name">
          <el-input v-model="reimbursePrivateDetail.bank_card_name" placeholder="请输入开户户名"/>
        </el-form-item>
        <el-form-item v-if="reimbursePrivateDetail.pay_type === 3" label="开户账号" prop="bank_account">
          <el-input v-model="reimbursePrivateDetail.bank_account" placeholder="请输入开户账号"/>
        </el-form-item>
        <el-form-item v-if="reimbursePrivateDetail.pay_type === 2" label="支票抬头" prop="cheque_payable">
          <el-input v-model="reimbursePrivateDetail.cheque_payable" placeholder="请输入支票抬头"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="privateDialogVisible = false">取 消</el-button>
        <el-button type="primary" size="mini" @click="saveReimbursePrivateDetail">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import FlowBtnRow from '@/components/FlowBtnRow/index'
import {
  actualDeleteData,
  deleteData,
  getDetail,
  pass,
  returnBack,
  save,
  saveAndBegin
} from '@/api/reimbursement/ordinary/ordinary'
import { add, amountToBigStr } from '@/utils/amount'
import { getToken } from '@/utils/auth'
import { upFileUrl } from '@/api/others'
import { get_customer_commission_by_sale_id, list_by_user_id, list_for_market_by_contract_id } from '@/api/saleOrder'
import printHtml from '@/utils/print'
import { list_all3rd_bycode_contrain_del_close } from '@/api/business/setting/dict'
import { get_contract_list_by_reimburse } from '@/api/contract'
import { formatDate } from '@/utils/util'

const id_reg = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/

export default {
  name: 'ReimbursementInfo',
  components: {
    FlowBtnRow
  },
  data() {
    var checkAccount = (rule, value, callback) => {
      if (value === '' || value === null) {
        callback(new Error('请输入金额'))
      } else {
        const reg = /(^[1-9]{1}[0-9]*$)|(^[0-9]*\.[0-9]{2}$)/
        if (reg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入合法金额'))
        }
      }
    }
    var checkNo = (rule, value, callback) => {
      if (!value) {
        // return callback(new Error('证件号码为空'))
        return callback()
      }
      if (!id_reg.test(value)) {
        return callback(new Error('证件号码格式不正确'))
      } else {
        return callback()
      }
    }
    return {
      is_print: false,
      cuForm: {
        name: null, // 报销名称
        type: 1, // 1：普通 2：维护报销 3：客提
        submit_time: null, // 提交时间
        contract_id: null, // 合同id
        contract_num: null, // 合同编号
        part_a: null, // 合同甲方名称
        contract_begin_date: null, // 合同开始时间
        contract_end_date: null, // 合同结束时间
        bill_sale_id: null, // 销售单id
        actual_execute_time_start: null, // 销售单开始时间
        actual_execute_time_end: null, // 销售单结束时间
        sale_contract_num: null, // 销售单合同编号
        total_amount: 0, // 总金额
        reimburseApplyDetailList: [ // 付款详情
          {
            category_name: null, // 类目名称
            category_id: null, // 类目id
            product_name: null, // 品名
            unit: null, // 单位
            quantity: undefined, // 数量
            amount: null, // 金额
            reason: null // 用途
          },
          {
            category_name: null, // 类目名称
            category_id: null, // 类目id
            product_name: null, // 品名
            unit: null, // 单位
            quantity: undefined, // 数量
            amount: null, // 金额
            reason: null // 用途
          },
          {
            category_name: null, // 类目名称
            category_id: null, // 类目id
            product_name: null, // 品名
            unit: null, // 单位
            quantity: undefined, // 数量
            amount: null, // 金额
            reason: null // 用途
          }
        ],
        reimbursePublicDetailList: [], // 对公报销详情
        reimbursePrivateDetailList: [], // 对私报销详情
        reimburseApplyAttachmentList: [] // 附件信息
      },
      is_created: false,
      old_type: 1,
      formLoading: false,
      uploadHeaders: {},
      upFileUrl,
      fileList: [],
      sale_list: [],
      contract_list: [],
      category_arr: [],
      edit: false,
      reimbursePublicDetail: {
        company_name: null, // 公司名称
        amount: null, // 金额
        bank_name: null, // 开户行名称
        bank_account: null // 开户账户
      },
      reimbursePrivateDetail: {
        name: null, // 姓名
        id_card: null, // 证件号码
        amount: null, // 金额
        pay_type: 1, // 支付方式 1：现金 2：支票 3：网银汇划
        bank_name: null, // 银行名称
        bank_account: null, // 开户账户
        bank_card_name: null, // 开户户名
        cheque_payable: null // 支票抬头
      },
      reimbursePrivateDetailRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ], // 姓名
        id_card: [
          { required: false, message: '请输入证件号码', trigger: 'blur' },
          { validator: checkNo, trigger: 'blur' }
        ], // 证件号码
        pay_type: [
          { required: true, message: '请选择支付方式', trigger: 'change' }
        ],
        amount: [
          { required: true, message: '请输入金额', trigger: 'blur' },
          { validator: checkAccount, trigger: 'blur' }
        ], // 金额
        bank_name: [
          { required: true, message: '请输入银行名称', trigger: 'blur' }
        ], // 银行名称
        bank_account: [
          { required: true, message: '请输入开户账户', trigger: 'blur' }
        ], // 开户账户
        bank_card_name: [
          { required: true, message: '请输入开户户名', trigger: 'blur' }
        ], // 开户户名
        cheque_payable: [
          { required: true, message: '请输入支票抬头', trigger: 'blur' }
        ] // 支票抬头
      },
      reimbursePublicDetailRules: {
        company_name: [
          { required: true, message: '请输入公司名称', trigger: 'blur' }
        ],
        bank_name: [
          { required: true, message: '请输入开户行名称', trigger: 'blur' }
        ],
        bank_account: [
          { required: true, message: '请输入开户账号', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '请输入金额', trigger: 'blur' },
          { validator: checkAccount, trigger: 'blur' }
        ]
      },
      publicDialogVisible: false,
      privateDialogVisible: false,
      privateIndex: -1,
      index: -1,
      commission: null,
      notification: null,
      timer: null,
      loading: null,
      params: {}
    }
  },
  computed: {
    userName() {
      return this.cuForm.real_name ? this.cuForm.real_name : this.$store.state.user.name
    },
    userId() {
      return this.$store.state.user.id
    },
    bigMoneyStr() {
      return amountToBigStr(this.cuForm.total_amount)
    },
    formDisabled() {
      return this.cuForm.flow_status == 3 || this.cuForm.flow_status == 4
    }
  },
  watch: {
    'cuForm.reimburseApplyDetailList': {
      handler(val) {
        let tmp = 0
        if (val.length > 0) {
          for (let i = 0; i < val.length; i++) {
            if (val[i].amount && !isNaN(val[i].amount)) {
              tmp = add(tmp, val[i].amount)
            }
          }
        }
        this.cuForm.total_amount = tmp
      },
      deep: true
    }
  },
  created() {
    if (getToken()) {
      this.uploadHeaders['Authorization'] = getToken()
    }
    this.initCategoryArr()
    const uuid = this.$route.query.uuid
    const params = this.$store.state.keep.pageParamsMap.get(uuid)
    this.params = params
    if (params) {
      if (params.id) {
        this.cuForm.id = params.id
        this.getDetail(this.cuForm.id)
      }
      if (params.is_created) {
        this.is_created = params.is_created
        this.cuForm.submit_time = formatDate(new Date())
      }
      if (params.handle_param) {
        this.cuForm.id = params.handle_param.id
        this.getDetail(this.cuForm.id)
      }
    }
  },
  beforeDestroy() {
    if (this.notification) {
      this.notification.close()
    }
  },
  methods: {
    save() {
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      save(this.cuForm).then(
        res => {
          if (res.code === 200) {
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.closeThisPage()
          } else {
            this.$message.error('操作失败')
          }
          loading.close()
        }
      ).catch(() => {
        loading.close()
      })
    },
    submit() {
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      saveAndBegin(this.cuForm).then(
        res => {
          if (res.code === 200) {
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.closeThisPage()
          } else {
            this.$message.error('操作失败')
          }
          loading.close()
        }
      ).catch(() => {
        loading.close()
      })
    },
    pass(option) {
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      pass({
        id: this.cuForm.id,
        wf_check_opinion: option
      }).then(
        res => {
          if (res.code === 200) {
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.closeThisPage()
          } else {
            this.$message.error('操作失败')
          }
          loading.close()
        }
      ).catch(() => {
        loading.close()
      })
    },
    returnBack(option) {
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      returnBack({
        id: this.cuForm.id,
        wf_check_opinion: option
      }).then(
        res => {
          if (res.code === 200) {
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.closeThisPage()
          } else {
            this.$message.error('操作失败')
          }
          loading.close()
        }
      ).catch(() => {
        loading.close()
      })
    },
    remove() {
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      deleteData(this.cuForm.id).then(
        res => {
          if (res.code === 200) {
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.closeThisPage()
          } else {
            this.$message.error('操作失败')
          }
          loading.close()
        }
      ).catch(() => {
        loading.close()
      })
    },
    actualDelete() {
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      actualDeleteData(this.cuForm.id).then(
        res => {
          if (res.code === 200) {
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.closeThisPage()
          } else {
            this.$message.error('操作失败')
          }
          loading.close()
        }
      ).catch(() => {
        loading.close()
      })
    },
    getDetail(id) {
      this.formLoading = true
      getDetail({ id: id }).then(
        res => {
          this.formLoading = false
          this.cuForm = res.data
          this.cuForm.reimburseApplyAttachmentList = this.cuForm.reimburseApplyAttachmentList.map(item => {
            return {
              name: item.origin_name,
              origin_name: item.origin_name,
              url: item.url
            }
          })
          if (this.cuForm.type === 2) {
            this.initContractArr()
          }
          if (this.cuForm.type === 3) {
            this.initSaleList()
            const amount = this.cuForm.reimbursePrivateDetailList[0].amount
            this.getCommission(this.cuForm.bill_sale_id, amount)
          }
        }
      )
    },
    closeThisPage() {
      if (this.notification) {
        this.notification.close()
      }
      this.$store.dispatch('tagsView/closeCurPage')
    },
    // 增加一行
    addItem() {
      this.cuForm.reimburseApplyDetailList.push({
        category_name: null, // 类目名称
        category_id: null, // 类目id
        product_name: null, // 品名
        unit: null, // 单位
        quantity: undefined, // 数量
        amount: null, // 金额
        reason: null // 用途
      })
    },
    removeItem(type, index) {
      this.$confirm('确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (type === 1) {
          this.cuForm.reimburseApplyDetailList.splice(index, 1)
        } else if (type === 2) {
          this.cuForm.reimbursePrivateDetailList.splice(index, 1)
        } else {
          this.cuForm.reimbursePublicDetailList.splice(index, 1)
        }
      }).catch(() => {

      })
    },
    handlePreview(file) {
      window.open(file.url, '_blank')
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    onRemove(file) {
      this.cuForm.reimburseApplyAttachmentList = this.cuForm.reimburseApplyAttachmentList.filter(item => item.url === file.url)
    },
    beforeUpload() {
      this.loading = this.$loading({
        lock: true,
        text: '上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    uploadError() {
      this.loading.close()
    },
    uploadSuccess(response, file, fileList) {
      console.log(response, file)
      this.loading.close()
      this.cuForm.reimburseApplyAttachmentList.push({
        name: file.name,
        origin_name: file.name,
        url: response.data
      })
    },
    initSaleList() {
      list_by_user_id({
        reimburse_id: this.cuForm.id
      }).then(res => {
        this.sale_list = res.data
      }).catch(() => {
        this.sale_list = []
      })
    },
    initContractArr() {
      get_contract_list_by_reimburse().then(res => {
        this.contract_list = res.data
      }).catch(() => {
        this.contract_list = []
      })
    },

    print() {
      this.is_print = true
      this.$nextTick(() => {
        // 获取局部html，也就是打印的区域
        const printData = document.querySelector('#printContent').innerHTML
        printHtml(printData).then(() => {
          this.is_print = false
        }).catch(() => {
          this.is_print = false
          this.$message.error('打印失败，请联系管理员')
        })
      })
    },
    initCategoryArr() {
      list_all3rd_bycode_contrain_del_close(
        { code: 'bxxg-lm' }
      ).then(res => {
        this.category_arr = res.data
      })
    },
    onChange(item, val) {
      const find = this.category_arr.find(tmp => tmp.id === val)
      if (find) {
        item.category_name = find.name
      } else {
        item.category_name = ''
      }
    },
    showPublicDialog(index = -1) {
      this.publicDialogVisible = true
      this.index = index
      if (index !== -1) {
        this.reimbursePublicDetail = Object.assign({}, this.cuForm.reimbursePublicDetailList[index])
      }
    },
    closePublicDialog() {
      this.reimbursePublicDetail = {
        company_name: null, // 公司名称
        amount: null, // 金额
        bank_name: null, // 开户行名称
        bank_account: null // 开户账户
      }
      this.$nextTick(() => {
        this.$refs.reimbursePublicDetailForm.clearValidate()
      })
    },
    saveReimbursePublicDetail() {
      this.$refs.reimbursePublicDetailForm.validate(flag => {
        if (flag) {
          if (this.index === -1) { // 增加
            this.cuForm.reimbursePublicDetailList.push(Object.assign({}, this.reimbursePublicDetail))
          } else {
            this.cuForm.reimbursePublicDetailList.splice(this.index, 1, Object.assign({}, this.reimbursePublicDetail))
          }
          this.publicDialogVisible = false
        }
      })
    },
    typeChange(type) {
      if (this.notification) {
        this.notification.close()
      }
      if (this.cuForm.reimbursePublicDetailList.length === 0 && this.cuForm.reimbursePrivateDetailList.length === 0) {
        if (type === 1) {
          this.clearContractData()
          this.clearSaleData()
          this.cuForm.reimbursePublicDetailList = []
          this.cuForm.reimbursePrivateDetailList = []
        } else if (type === 2) {
          this.clearSaleData()
          this.initContractArr()
          this.cuForm.reimbursePrivateDetailList = []
          this.cuForm.reimbursePublicDetailList = []
        } else {
          this.clearContractData()
          this.initSaleList()
          this.cuForm.reimbursePrivateDetailList = []
          this.cuForm.reimbursePublicDetailList = []
        }
        this.old_type = type
      } else {
        this.$confirm('切换类型会导致对公对私中数据丢失，确定切换?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (type === 1) {
            this.clearContractData()
            this.clearSaleData()
            this.cuForm.reimbursePublicDetailList = []
            this.cuForm.reimbursePrivateDetailList = []
          } else if (type === 2) {
            this.clearSaleData()
            this.initContractArr()
            this.cuForm.reimbursePrivateDetailList = []
            this.cuForm.reimbursePublicDetailList = []
          } else {
            this.clearContractData()
            this.initSaleList()
            this.cuForm.reimbursePrivateDetailList = []
            this.cuForm.reimbursePublicDetailList = []
          }
          this.old_type = type
        }).catch(() => {
          this.cuForm.type = this.old_type
        })
      }
    },
    clearContractData() {
      this.cuForm.contract_id = null
      this.cuForm.contract_num = null
      this.cuForm.part_a = null
      this.cuForm.contract_begin_date = null
      this.cuForm.contract_end_date = null
    },
    clearSaleData() {
      this.cuForm.bill_sale_id = null
      this.cuForm.sale_contract_num = null
      this.cuForm.actual_execute_time_end = null
      this.cuForm.actual_execute_time_start = null
    },
    saveReimbursePrivateDetail() {
      this.$refs.reimbursePrivateDetailForm.validate(flag => {
        if (flag) {
          if (this.cuForm.type === 3) {
            if (this.reimbursePrivateDetail.amount <= this.commission.total_execute_amount) {
              if (this.privateIndex === -1) { // 增加
                this.cuForm.reimbursePrivateDetailList.push(Object.assign({}, this.reimbursePrivateDetail))
              } else {
                this.cuForm.reimbursePrivateDetailList.splice(this.index, 1, Object.assign({}, this.reimbursePrivateDetail))
              }
              this.privateDialogVisible = false
            } else {
              this.$message.error('客提不能超过执行金额总和')
            }
          } else {
            if (this.privateIndex === -1) { // 增加
              this.cuForm.reimbursePrivateDetailList.push(Object.assign({}, this.reimbursePrivateDetail))
            } else {
              this.cuForm.reimbursePrivateDetailList.splice(this.index, 1, Object.assign({}, this.reimbursePrivateDetail))
            }
            this.privateDialogVisible = false
          }
        }
      })
    },
    closePrivateDialog() {
      this.reimbursePrivateDetail = {
        name: null, // 姓名
        id_card: null, // 证件号码
        amount: null, // 金额
        pay_type: 1, // 支付方式 1：现金 2：支票 3：网银汇划
        bank_name: null, // 银行名称
        bank_account: null, // 开户账户
        bank_card_name: null, // 开户户名
        cheque_payable: null // 支票抬头
      }
      this.$nextTick(() => {
        this.$refs.reimbursePrivateDetailForm.clearValidate()
      })
    },
    showPrivateDialog(index = -1) {
      this.privateDialogVisible = true
      this.privateIndex = index
      if (index !== -1) {
        this.reimbursePrivateDetail = Object.assign({}, this.cuForm.reimbursePrivateDetailList[index])
      }
    },
    billSaleChange(id) {
      this.cuForm.reimbursePrivateDetailList = []
      let amount = null
      if (this.cuForm.reimbursePrivateDetailList && this.cuForm.reimbursePrivateDetailList.length) {
        amount = this.cuForm.reimbursePrivateDetailList[0].amount
      }
      if (id) {
        this.getCommission(id, amount)
      }
    },
    inputChange(val) {
      if (this.cuForm.type === 3) {
        clearTimeout(this.timer)
        const that = this
        this.timer = setTimeout(() => {
          that.getCommission(that.cuForm.bill_sale_id, val)
        }, 1000)
      }
    },
    getCommission(id, amount) {
      if (id) {
        get_customer_commission_by_sale_id({
          id,
          amount
        }).then(res => {
          this.commission = res.data
          var str = '<div>'
          str += '<span>刊例总价总和：' + res.data.total_price + '</span><br/>'
          str += '<span>执行金额总和：' + res.data.total_execute_amount + '</span><br/>'
          if (res.data.real_gear) {
            str += '<span style="color: red">原始档位：' + res.data.source_gear.gear + '档</span><br/>'
            str += '<span style="color: red">真实档位：' + res.data.real_gear.gear + '档</span><br/>'
          } else {
            str += '<span>档位：' + res.data.source_gear.gear + '档</span><br/>'
          }
          str += res.data.max_quota ? '<span>最大客提额度：' + '<span style="color: red">' + res.data.max_quota + '</span>' + '元</span><br/>' : ''
          str += '</div>'
          if (this.notification) {
            this.notification.close()
          }
          this.notification = this.$notify({
            title: '组信息',
            dangerouslyUseHTMLString: true,
            position: 'bottom-right',
            duration: 0,
            showClose: false,
            message: str
          })
        })
      }
    },
    checkCuForm() {
      if (this.cuForm.type === 1) {
        this.$message.error('最少有一个对私报销或者对公报销')
        return this.cuForm.reimbursePublicDetailList.length + this.cuForm.reimbursePrivateDetailList.length > 0
      } else if (this.cuForm.type === 2) {
        this.$message.error('最少有一个对私报销')
        return this.cuForm.reimbursePrivateDetailList.length > 0
      } else {
        this.$message.error('请添加对私报销')
        return this.cuForm.reimbursePrivateDetailList.length === 1
      }
    }
  }
}
</script>

<style scoped>

.mailTable {
  width: 100%;
  font-size: 14px;
  margin: 0 auto 10px auto;
  border-collapse: collapse;
}

.mailTable tr td {
  height: 60px;
  line-height: 35px;
  box-sizing: border-box;
  padding: 0 10px;
  border-bottom: 1px solid #E6EAEE;
  border-right: 1px solid #E6EAEE;
}

.firstTr td {
  border-top: 1px solid #E6EAEE;
}

.firstTd {
  border-left: 1px solid #E6EAEE;
}

.mailTable tr td.column {
  text-align: center;
  /*border: 1px solid #8c939d;*/
}

.tip {
  color: red;
}

.header {
  padding-top: 20px;
  text-align: center;
  font-size: 25px;
  font-weight: bold;
  margin: 10px auto;
}

/deep/ .mailTable .el-form-item {
  margin-bottom: 0;
}

/deep/ .el-textarea.is-disabled .el-textarea__inner {
  background-color: white;
  color: black;
}

/deep/ .el-input.is-disabled .el-input__inner {
  background-color: white;
  color: black;
}

#printContent {
  padding-top: 20px;
}

/deep/ .el-radio__input.is-disabled + span.el-radio__label {
  color: black;
}

/deep/ .el-radio__input.is-checked .el-radio__inner {
  border-color: #409EFF;
  background: #409EFF
}

/deep/ .el-radio__input.is-disabled.is-checked .el-radio__inner::after {
  width: 4px;
  height: 4px;
  border-radius: 100%;
  background-color: #FFF;
}

/deep/ .upload_none .el-upload--text {
  display: none;
}
</style>
